package ThreadService;

import service.PureLogDb;

import java.io.*;
import java.net.Socket;
import java.util.Locale;

public class ServerThread implements Runnable{

    private Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        PureLogDb db = new PureLogDb();
        try(BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] msgs = line.split(" ");
                //判断过来的是 set，delete，get命令，根据不同的命令进行不同的实现
                if ("SET".equals(msgs[0].toUpperCase(Locale.ROOT)))
                    db.putVal(msgs[1], msgs[2]);
                else if ("DELETE".equals(msgs[0].toUpperCase(Locale.ROOT)))
                    db.rmVal(msgs[1]);
                else if ("GET".equals(msgs[0].toUpperCase(Locale.ROOT))) {
                    String value = db.getVal(msgs[1]);
                    bw.write(value + "\n");
                    bw.flush();
                    System.out.println(value);
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        }

    }
}
